package com.jianjun.project.system.dict;


import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.common.exception.ServiceException;
import com.jianjun.common.util.DictUtils;
import com.jianjun.project.common.model.SysDictData;
import com.jianjun.project.common.model.SysDictType;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 字典 业务层处理
 *
 * @author source
 */
public class SysDictTypeService {
    private final SysDictType dao = new SysDictType().dao();
    @Inject
    SysDictDataService dictDataService;

    /**
     * 项目启动时，初始化字典到缓存
     */
    public void init() {
        loadingDictCache();
    }


    public Page<SysDictType> paginate(SysDictType model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysDictType", Kv.by("cond", model.toMap()).set(model.getColumnAsc()));
        return dao.paginate(model.getPageNum(), model.getPageSize(), sqlParaDb);
    }

    /**
     * 根据条件分页查询字典类型
     */
    public List<SysDictType> selectDictTypeList(Model<SysDictType> model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysDictType", Kv.by("cond", model.toMap()));
        return dao.find(sqlParaDb);
    }

    /**
     * 根据所有字典类型
     *
     * @return 字典类型集合信息
     */
    public List<SysDictType> selectDictTypeAll() {
        return dao.findAll();
    }


    /**
     * 根据字典类型ID查询信息
     *
     * @param dictId 字典类型ID
     * @return 字典类型
     */
    public SysDictType selectDictTypeById(Long dictId) {
        return dao.findById(dictId);
    }


    /**
     * 批量删除字典类型信息
     *
     * @param dictIds 需要删除的字典ID
     */
    public void deleteDictTypeByIds(Long[] dictIds) {
        for (Long dictId : dictIds) {
            SysDictType dictType = selectDictTypeById(dictId);
            if (dictDataService.countDictDataByType(dictType.getDictType()) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", dictType.getDictName()));
            }
            dao.deleteById(dictId);
            DictUtils.removeDictCache(dictType.getDictType());
        }
    }

    /**
     * 加载字典缓存数据
     */
    public void loadingDictCache() {
        SysDictData model = new SysDictData();
        model.setStatus("0");
        Map<String, List<SysDictData>> dictDataMap = dictDataService.selectDictDataList(model).stream().collect(Collectors.groupingBy(SysDictData::getDictType));
        for (Map.Entry<String, List<SysDictData>> entry : dictDataMap.entrySet()) {
            DictUtils.setDictCache(entry.getKey(), entry.getValue().stream().sorted(Comparator.comparing(SysDictData::getDictSort)).collect(Collectors.toList()));
        }
    }

    /**
     * 清空字典缓存数据
     */
    public void clearDictCache() {
        DictUtils.clearDictCache();
    }

    /**
     * 重置字典缓存数据
     */
    public void resetDictCache() {
        clearDictCache();
        loadingDictCache();
    }


    /**
     * 新增保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */
    public boolean insertDictType(SysDictType dict) {
        dict.setCreateTime(new Date());
        boolean res = dict.save();
        if (res) {
            DictUtils.setDictCache(dict.getDictType(), null);
        }
        return res;
    }

    /**
     * 修改保存字典类型信息
     *
     * @param dict 字典类型信息
     * @return 结果
     */

    public boolean updateDictType(SysDictType dict) {
        dict.setUpdateTime(new Date());
        boolean res = dict.update();
        if (res) {
            SysDictData model = new SysDictData();
            model.setDictType(dict.getDictType());
            List<SysDictData> dictDatas = dictDataService.selectDictDataList(model);
            DictUtils.setDictCache(dict.getDictType(), dictDatas);
        }
        return res;
    }


    /**
     * 校验字典类型称是否唯一
     *
     * @param dict 字典类型
     * @return 结果
     */
    public boolean checkDictTypeUnique(SysDictType dict) {
        long dictId = Objects.isNull(dict.getDictId()) ? -1L : dict.getDictId();
        SysDictType model = new SysDictType();
        model.setDictType(dict.getDictType());
        SqlPara sqlParaDb = Db.getSqlPara("querySysDictType", Kv.by("cond", model.toMap()));
        SysDictType dictType = dao.findFirst(sqlParaDb);
        if (Objects.nonNull(dictType) && dictType.getDictId() != dictId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}
